const bcrypt = require("bcryptjs");
const Redis = require("ioredis");

const client = new Redis({
  port: 6379, // Redis port
  host: "8.134.65.55", // Redis host
  family: 4, // 4 (IPv4) or 6 (IPv6)
  password: "123456",
  db: 0,
});
const { getUserInfo } = require("../service/user/user.service");
const {
  phoneNumberCannotBeEmpty,
  phoneNumberFormatError,
  phoneNumberAlreadyExists,
  userRegisterError,
  userDoesNotExist,
  InfinityError,
  userLoginError,
  verificationCodeError,
  verificationCodeExpired,
} = require("../constant/err.type");

const userValidator = async (ctx, next) => {
  const { phone_number } = ctx.request.body;
  if (!phone_number) {
    console.error("手机号不能为空", ctx.request.body);
    ctx.app.emit("error", phoneNumberCannotBeEmpty, ctx);
    return;
  }
  if (phone_number.length !== 11) {
    console.error("手机号格式错误", ctx.request.body);
    ctx.app.emit("error", phoneNumberFormatError, ctx);
    return;
  }
  await next();
};

const verifyUser = async (ctx, next) => {
  const { phone_number } = ctx.request.body;
  // if (await getUserInfo({ phone_number })) {
  //   ctx.status = 409;
  //   console.error("手机号已存在", ctx.request.body);

  //   ctx.app.emit("error",phoneNumberAlreadyExists, ctx);
  //   return;
  // }
  try {
    const res = await getUserInfo({ phone_number });
    if (res) {
      ctx.status = 200;
      console.error("手机号已存在", ctx.request.body);
      ctx.body = phoneNumberAlreadyExists;
      return;
    }
  } catch (err) {
    console.error("获取用户信息错误", err);
    ctx.app.emit("error", userRegisterError, ctx);
    return;
  }
  await next();
};
const verifyLogin = async (ctx, next) => {
  const { phone_number, password } = ctx.request.body;
  try {
    const res = await getUserInfo({ phone_number });
    if (!res) {
      ctx.status = 401;
      console.error("用户不存在", ctx.request.body);
      ctx.app.emit("error", userDoesNotExist, ctx);
      return;
    }
    if (!bcrypt.compareSync(password, res.password)) {
      console.error("用户或密码错误", ctx.request.body);
      ctx.body = InfinityError;
      return;
    }
  } catch (err) {
    console.error("用户登录失败", err);
    ctx.app.emit("error", userLoginError, ctx);
    return;
  }
  await next();
};
// 验证用户是否存在
const hasUser = async (ctx, next) => {
  const { phone_number } = ctx.request.body;
  try {
    const res = await getUserInfo({ phone_number });
    if (!res) {
      ctx.status = 401;
      console.error("用户不存在", ctx.request.body);
      ctx.app.emit("error", userDoesNotExist, ctx);
      return;
    }
  } catch (err) {
    ctx.status = 401;
    console.error("获取用户信息失败", ctx.request.body);
    ctx.app.emit("error", userDoesNotExist, ctx);
    return;
  }
  await next();
};
// 验证验证码
const hasVerificationCode = async (ctx, next) => {
  const { phone_number, verification_code } = ctx.request.body;
  try {
    // const res = await getUserInfo({ phone_number });
    const verificationCode = await client.get(phone_number);
    // if (!res) {
    //   ctx.status = 401;
    //   console.error("用户不存在", ctx.request.body);
    //   ctx.app.emit("error", userDoesNotExist, ctx);
    //   return;
    // }
    if (verificationCode === null) {
      console.error("验证码不存在", ctx.request.body);
      ctx.body = verificationCodeExpired;
      return;
    } else if (verificationCode !== verification_code) {
      console.error("验证码错误", ctx.request.body);
      ctx.body = verificationCodeError;
      return;
    }
  } catch (err) {
    console.error("操作失败", err);
    ctx.app.emit("error", userLoginError, ctx);
    return;
  }
  await next();
};
//验证密码
const cryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash;
  await next();
};

module.exports = {
  userValidator,
  verifyUser,
  cryptPassword,
  verifyLogin,
  hasVerificationCode,
  hasUser,
};
